package com.example.boot05.Controller;

import com.example.boot05.entity.Product;
import com.example.boot05.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Name: ProductController
 * @Author: 西风残叶
 * @Company: 朝兮网络工作室
 * @Data: 2023/11/11 18:23
 */
@RestController
public class ProductController {
    @Autowired
    ProductMapper mapper;

    /**
     * 插入数据
     * @param product :实体类对象
     * @return :返回插入成功页面
     */
    @RequestMapping("/insert")
    public String insert(Product product){
        System.out.println("product" +product);
        mapper.insert(product);
        return "添加成功! <a href='/'>返回首页</a>";
    }

    /**
     * 商品列表
     * @return : 返回一个表格
     */
    @RequestMapping("/select")
    public String select(){
        List<Product> list = mapper.select();
        String html = "<center><table border='1'>";
        html += "<h1>商品列表</h1>";
        html += "<tr><th>id</th><th>标题</th><th>价格</th><th>库存</th><th>操作</th></tr>";
        // 遍历商品集合
        for (Product p : list) {
            html += "<tr>";
            html += "<td>" + p.getId() + "</td>";
            html += "<td>" + p.getTitle() + "</td>";
            html += "<td>" + p.getPrice() + "</td>";
            html += "<td>" + p.getNum() + "</td>";
            //             /delete?id=5
            html += "<td><a href='/delete?id=" + p.getId() + "'>删除</a></td>";
            html += "</tr>";
        }
        html += "</table></center>";
        return html;
    }

    /**
     * 删除商品
     * @param id :删除商品的id
     * @return :返回删除结果
     */
    @RequestMapping("/delete")
    public String delete(int id){
        mapper.deleteByid(id);
        return "删除成功! <a href='/select'>返回商品列表</a>";
    }

    @RequestMapping("/update")
    public String update(Product product){
        mapper.update(product);
        return "修改成功!<a href='/'>返回首页</a>";
    }
}